<?

class Main {

    public function __construct() {
        $this->db = Database::Init();
        $this->site = $this->GetSite();
        $this->template = $this->GetTemplate();
    }

    function GetSite($id = false) {
        $process = $this->db->select()
                        ->field(array('s.*', 'l.code' => 'lang'))
                        ->table('sites', 's')
                        ->table('languages', 'l')
                        ->cond('l.id', 's.lang')->noquotes()
        ;
        if ($id) {
            $process->cond('id', $id);
        } else {
            $process->cond('is_default', 1);
        }
        $result = $process->execute();

        return $result->Object();
    }

    function GetTemplate() {
        $result = new stdClass();
        $map = unserialize($this->site->template_map);
        unset($this->site->template_map);
        $tpl = "default";
        $uriData = parse_url($_SERVER['REQUEST_URI']);

        foreach ($map as $template) {
            if ($template['type'] == "path" && preg_match("#" . $template['condition'] . "#", $uriData['path'])) {
                $tpl = $template['template'];
            }
            if ($template['type'] == "site" && $template['condition'] == $this->site->code) {
                $tpl = $template['template'];
            }
        }
        $result->code = $tpl;
        $result->path = TEMPLATES . "/$tpl";
        $result->uri = pathToUri(TEMPLATES . "/$tpl");
        $result->map = $map;
        return $result;
    }

    public static function AddHeadStyle($uri) {
        preg_match("#.(less|css)$#", $uri, $data);
        $rel = $data[1] == "css" ? "stylesheet" : "stylesheet/less";
        $str = "<link type=\"text/css\" rel=\"$rel\" href=\"$uri\">";
        Buffer::Add('HEAD_STYLE', $str);
    }

    public static function AddHeadScript($uri) {
        if (preg_match("#.js$#", $uri)) {
            $str = "<script type=\"text/javascript\" src=\"$uri\"></script>";
            Buffer::Add('HEAD_SCRIPT', $str);
        }
    }

    public static function GetHeadStyles() {
        return Buffer::Get('HEAD_STYLE');
    }

    public static function GetHeadScripts() {
        return Buffer::Get('HEAD_SCRIPT');
    }
    
    public static function Component($ns_name, $tpl = false, $params = array()){
        $tpl = $tpl ? $tpl : "default";
        list($ns, $name) = explode(":", $ns_name);
        $filename = KERNEL."/components/$ns/$name/$name.com.php";
        if(file_exists($filename)){
            $result = array();
            include $filename;
        }
        
        $filename = KERNEL."/components/$ns/$name/views/$tpl/view.php";
        if(file_exists($filename)){
            include $filename;
        }
    }
}
